import { _decorator, Animation, Collider2D, Component, Contact2DType, IPhysics2DContact, Node, RigidBody2D } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EnemyAPI')
export class EnemyAPI extends Component {

    @property
    speed: number = 300; // 敌机移动速度

    @property(Animation)
    enemyAnimation: Animation = null; // 敌机动画组件

    @property
    HP: number = 10; // 敌机生命值


    collider: Collider2D = null;

    @property
    animatOne: string = ''; // 受伤动画名称
    @property
    animatTwo: string = ''; // 死亡动画名称


    start() {
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        } else {
            console.log('组件未找到')
        }
        // this.enemyAnimation.play(); // 播放敌机移动动画
    }
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {

        // 处理碰撞开始

        this.HP -= 10; // 每次碰撞减少1点生命值
        if (this.HP > 0) {
            // 播放受伤动画
            this.enemyAnimation.play(this.animatOne);

        } else {
            // 播放死亡动画

            this.enemyAnimation.play(this.animatTwo);
            if (this.collider) {
                this.collider.enabled = false; // 禁用碰撞器，防止重复触发
            }
            this.scheduleOnce(() => {
                this.node.destroy(); // 延迟销毁敌机节点
            }, 1); // 假设动画持续1秒
        }


    }

    update(deltaTime: number) {
        let position = this.node.position;
        // 每帧向下移动
        this.node.setPosition(position.x, position.y - this.speed * deltaTime, position.z);
        if (position.y < -700) {
            // 如果超出边界，销毁节点
            this.node.destroy();
        }
    }

    protected onDestroy() {
        if (this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }


    }
}

